<template>
  <div class="article-view">
    <el-card v-if="article" class="article-card" shadow="always">
      <h1 class="title">{{ article.title }}</h1>
      <div class="meta">
        <span>作者：{{ article.username }}</span>
        <span>发布时间：{{ formatDate(article.createTime) }}</span>
      </div>
      <el-divider></el-divider>
      <div class="content" v-html="article.content"></div>
    </el-card>

    <CommentList
      v-if="article && article.id"
      :postId="article.id"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import CommentList from "@/components/CommentList.vue";
const route = useRoute();
const article = ref(null);

// 格式化时间
const formatDate = (time) => {
  if (!time) return "";
  const d = new Date(time);
  return d.toLocaleString();
};

// 获取文章详情
const fetchArticle = async () => {
  const id = route.params.id;
  if (!id) return;
  try {
    const res = await request.get(`/api/posts/${id}`);
    console.log("📖 文章详情:", res);
    if (res.code === 200) {
      article.value = res.data;
    } else {
      ElMessage.error(res.message);
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("加载文章失败");
  }
};

onMounted(fetchArticle);
</script>

<style scoped>
.article-view {
  padding: 40px;
  max-width: 900px;
  margin: auto;
}

.article-card {
  padding: 30px;
}

.title {
  font-size: 26px;
  font-weight: bold;
  margin-bottom: 10px;
}

.meta {
  color: #999;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
}

.content {
  margin-top: 20px;
  line-height: 1.8;
  font-size: 16px;
  color: #333;
}
</style>
